const { reduceRight, map, evolve, inc } = require('ramda');
const puts = require('./src/utils/puts');
const logger = require('./src/utils/logger');
const error = require('./src/utils/error');

const createDownloadFolder = require('./src/createDownloadFolder');
const downloadVideos = require('./src/downloadVideos');
const getVideoContentURL = require('./src/egghead/getVideoContentURL');
const getLessonsUrl = require('./src/egghead/getLessonsUrl');

process.env.__PROJECT_PREFIX__ = '[video saver]';

// learn ramda.js series on egghead
// https://egghead.io/playlists/learn-ramda-js-ec318ad7

(async () => {
    const targetPath = './download';

    try {
        await createDownloadFolder(targetPath);

        // const seriesPageUrl = await puts('请输入egghead.io视频系列的地址：');
        const seriesPageUrl = 'https://egghead.io/playlists/learn-ramda-js-ec318ad7';
        const lessonsList = await getLessonsUrl(seriesPageUrl);
        logger('成功获取列表中所有lessons的信息');

        const videoList = await Promise.all(map(getVideoContentURL, lessonsList));
        logger('成功获取列表中所有视频地址');
        logger(`视频总数：${videoList.length}`);

        logger('开始视频下载');
        const downloadResult = await downloadVideos(videoList, targetPath);

        const downloadReport = reduceRight((curr, acc) => {
            if (curr) {
                return evolve({
                    success: inc,
                }, acc);
            }

            return evolve({
                fail: inc,
            }, acc);
        }, {
            success: 0,
            fail: 0,
            total: downloadResult.length,
        }, downloadResult);

        console.log('================ Download Summary ================');
        console.log(JSON.stringify(downloadReport, null, 4));

        process.exit(0);
    } catch (e) {
        throw error(e);
    }
})();
